package com.credit.mola.app.adapter

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.credit.mola.app.R
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.http.HttpHelper
import com.credit.mola.app.weight.font.NormalEditText
import com.credit.mola.lib_baseadapter.SikadwaRecyclerViewAdapter
import com.credit.mola.lib_baseadapter.SikadwaViewHolderHelper
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/18 10:43
 * @Annotation：流程常规通用适配器
 */
class ProcessCommonAdapter(recyclerView: RecyclerView?) : SikadwaRecyclerViewAdapter<JSONObject>(recyclerView) {

    //是否是通用样式，通用样式 tvTitle为加粗字体，非通用样式为默认字体
    var typeFaceStyle = Typeface.BOLD

    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "SELECT",
            "DATE_PICK",
            "GENDER_PICK",
            "SALARY_DAY_PICK",
            "BANK_PICK" ->{//出生日期、性别、通用选择、发薪日、收款账户银行名称
                return R.layout.item_process_common_select
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                return R.layout.item_process_contact_relation_select
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.item_process_common_mobile
            }
            "BANK_NUMBER_INPUT" -> {// 安哥拉 绑卡银行卡号
                return R.layout.item_process_common_input_bank_number
            }
            else -> {//输入框
                return R.layout.item_process_common_input
            }
        }
    }

    override fun setItemChildListener(helper: SikadwaViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.selectLayout)//选择
        helper.setItemChildClickListener(R.id.imgMobileBook)//选择联系人
        helper.setItemChildClickListener(R.id.tvMobile)
    }

    override fun fillData(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val tvTitle = helper.getTextView(R.id.tvTitle)
        tvTitle.text = findKeywordColor(ContextCompat.getColor(mContext,R.color.FFFF4D3E),model.optString("title"),"*")
        tvTitle.setTypeface(Typeface.DEFAULT,typeFaceStyle)

        when(model.optString("action")){
            "DATE_PICK",
            "GENDER_PICK",
            "SELECT",
            "SALARY_DAY_PICK",
            "BANK_PICK" ->{//出生日期、性别、通用选择、发薪日、收款账户银行名称
                showSelectView(helper,position,model)
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                showContactRelationView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showContactMobileView(helper,position,model)
            }
            "BANK_NUMBER_INPUT" -> {// 安哥拉 绑卡银行卡号
                showInputAngolaBankNumberView(helper,position,model)
            }
            else -> {//输入框
                showInputView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showInputView(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val editText = helper.getView<NormalEditText>(R.id.editText)
        editText.hint = model.optString("hint")
        var showText = ""
        val selectItem = model.optJSONObject("selectItem")
        selectItem?.let { selectItem ->
            showText = selectItem.optString("title")
        }
        editText.setText(showText)
        editText.setInputFocusChangeListener(object : NormalEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    model.put("showError",false)
                    editText.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
                }
            }
            override fun onCompleteAction(v: View?, remark: String) {
                val eventType = String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName"))
                HttpHelper.addEvent(eventType,remark)
            }
        })

        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }
        editText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        if (model.optBoolean("showError",false)){
            editText.setBackgroundResource(R.drawable.circle_fill_fffff2f2_frame_ffa30404)
        } else {
            editText.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
        }
    }

    /**
     * 安哥拉 银行卡号输入
     */
    @SuppressLint("SetTextI18n")
    private fun showInputAngolaBankNumberView(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject){
        val bankNumberLayout = helper.getView<LinearLayout>(R.id.bankNumberLayout)
        val bankCode = model.optString("bankCode","")
        val textBankCode = helper.getTextView(R.id.textBankCode)
        if (bankCode.isEmpty()){
            textBankCode.visibility = View.GONE
            helper.setVisibility(R.id.viewBankCodeLine,View.GONE)
        } else {
            textBankCode.visibility = View.VISIBLE
            textBankCode.text = bankCode
            helper.setVisibility(R.id.viewBankCodeLine,View.VISIBLE)
        }
        //提示语
        val editText = helper.getView<NormalEditText>(R.id.editText)
        editText.hint = model.optString("hint")

        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            if (selectItem != null) {
                showText = selectItem.optString("title")
            }
        }
        editText.setText(showText)
        editText.setInputFocusChangeListener(object : NormalEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    model.put("showError",false)
                    bankNumberLayout.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
                }
            }
            override fun onCompleteAction(v: View?, remark: String) {
                val eventType = String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName"))
                HttpHelper.addEvent(eventType,remark)
            }
        })

        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }
        editText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                s?.let {
                    val obj = JSONObject()
                    obj.put("title",s.toString())
                    obj.put("value",s.toString())
                    model.put("selectItem",obj)
                }
            }
        })
        if (model.optBoolean("showError",false)){
            bankNumberLayout.setBackgroundResource(R.drawable.circle_fill_fffff2f2_frame_ffa30404)
        } else {
            bankNumberLayout.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
        }
    }

    /**
     * 选择类型
     */
    private fun showSelectView(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject){
        if (!model.optBoolean("isShowItem",true)){
            helper.setVisibility(R.id.itemLayout,View.GONE)
            return
        }
        helper.setVisibility(R.id.itemLayout,View.VISIBLE)
        //提示语
        val hint = model.optString("hint")
        val tvValue = helper.getTextView(R.id.tvValue)
        tvValue.hint = hint

        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            if (selectItem != null) {
                showText = selectItem.optString("title")
            }
        }
        tvValue.text = showText
        val selectLayout = helper.getView<LinearLayout>(R.id.selectLayout)
        if (showText.isEmpty() && model.optBoolean("showError",false)){
            selectLayout.setBackgroundResource(R.drawable.circle_fill_fffff2f2_frame_ffa30404)
        } else {
            selectLayout.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
        }
    }

    /**
     * 联系人关系
     */
    private fun showContactRelationView(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val showHint: String = model.optString("hint")
        //选择关系
        val tvValue = helper.getTextView(R.id.tvValue)
        tvValue.hint = showHint
        //输入关系
        val editText = helper.getView<NormalEditText>(R.id.editText)
        //todo 此处确实选择Other时输入框的提示
        editText.hint = model.optString("relationOtherHint")
        editText.visibility = View.GONE

        var showTitle = ""
        var showOtherValue = ""
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            showTitle = selectItem.optString("title")
            if (showTitle == model.optString("relationOtherKey")){
                editText.visibility = View.VISIBLE
                if (selectItem.has("otherValue")){
                    showOtherValue = selectItem.optString("otherValue","")
                }
            }
        }
        tvValue.text = showTitle

        //关系为“Other”时，输入框允许输入
        editText.isEnabled = showTitle == model.optString("relationOtherKey")
        editText.setText(showOtherValue)
        editText.setInputFocusChangeListener(object : NormalEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    model.put("showError",false)
                    editText.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
                }
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(EventType.FORM.FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addEvent(eventType,remark)
            }
        })
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }

        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (model.has("selectItem")){
                    val selectItem = model.getJSONObject("selectItem")
                    selectItem.put("otherValue",s.toString())
                }
            }
        })
        val selectLayout = helper.getView<LinearLayout>(R.id.selectLayout)
        if (showTitle.isEmpty() && model.optBoolean("showError",false)){
            selectLayout.setBackgroundResource(R.drawable.circle_fill_fffff2f2_frame_ffa30404)
        } else {
            selectLayout.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
        }

        if (model.optBoolean("showError",false)){
            editText.setBackgroundResource(R.drawable.circle_fill_fffff2f2_frame_ffa30404)
        } else {
            editText.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
        }
    }

    /**
     * 联系电话
     */
    private fun showContactMobileView(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject){
        val selectLayout = helper.getView<RelativeLayout>(R.id.selectLayout)
        //提示语
        val hint = model.optString("hint")
        val textMobile = helper.getTextView(R.id.tvMobile)
        textMobile.hint = hint
        val editMobile = helper.getView<EditText>(R.id.editMobile)
        editMobile.hint = hint

        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            if (selectItem != null){
                showText = selectItem.optString("title")
            }
        }
        textMobile.text = showText
        editMobile.setText(showText)

        editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editMobile.clearFocus()
                true
            }
            false
        }
        editMobile.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                HttpHelper.addEvent(String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName")),editMobile.text.toString())
            } else {
                model.put("showError",false)
                selectLayout.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
            }
        }
        editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
        //设备是否支持通讯录选择联系人
        if (model.optBoolean("isContactPick")){
            helper.setVisibility(R.id.imgMobileBook,View.VISIBLE)
            //是否是审核账号
            val isConfigAccount = Configs.getSPBoolean(Configs.SPKEY.SIKADWA_IS_CONFIG_ACCOUNT)
            if(isConfigAccount){//审核账号 - 允许输入或选择
                textMobile.visibility = View.GONE
                editMobile.visibility = View.VISIBLE
            } else {//非审核账号只能选择
                textMobile.visibility = View.VISIBLE
                editMobile.visibility = View.GONE
            }
        } else {//不支持通讯录选择
            helper.setVisibility(R.id.imgMobileBook,View.INVISIBLE)
            textMobile.visibility = View.GONE
            editMobile.visibility = View.VISIBLE
        }

        if (showText.isEmpty() && model.optBoolean("showError",false)){
            selectLayout.setBackgroundResource(R.drawable.circle_fill_fffff2f2_frame_ffa30404)
        } else {
            selectLayout.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}